
<template>
  <div class="admin-dashboard">
    <!-- 第一行：概览卡片 -->
    <el-row :gutter="20" class="overview-section">
      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon document">
              <el-icon size="40"><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">今日支付订单</div>
              <div class="card-value">{{ overviewData.todayPaidOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon money">
              <el-icon size="40"><Money /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">今日支付金额</div>
              <div class="card-value">¥ {{ overviewData.todayPaidAmount }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon document">
              <el-icon size="40"><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">待完成订单</div>
              <div class="card-value highlight">{{ overviewData.pendingOrders }}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6" :lg="6">
        <el-card class="overview-card">
          <div class="card-content">
            <div class="card-icon document">
              <el-icon size="40"><Document /></el-icon>
            </div>
            <div class="card-info">
              <div class="card-title">待处理退款</div>
              <div class="card-value highlight">{{ overviewData.pendingRefunds }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：账户相关数据 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="section-title">账户相关数据</span>
          </template>
          <el-row :gutter="40" class="account-data">
            <el-col :span="8">
              <div class="data-item">
                <div class="data-label">总账余额</div>
                <div class="data-value balance">{{ accountData.totalBalance }}元</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <div class="data-label">今日进账</div>
                <div class="data-value income">{{ accountData.todayIncome }}元</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="data-item">
                <div class="data-label">今日出账</div>
                <div class="data-value outcome">{{ accountData.todayExpense }}元</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：金融相关数据 -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="section-title">金融相关数据</span>
          </template>
          <el-row :gutter="20" class="financial-data">
            <el-col :span="6">
              <div class="data-item">
                <div class="data-label">商品支付金额</div>
                <div class="data-value">{{ financialData.productPayment }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-label">配送费金额</div>
                <div class="data-value">{{ financialData.deliveryFee }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-label">退款金额</div>
                <div class="data-value">{{ financialData.refundAmount }}元</div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="data-item">
                <div class="data-label">配送费退款金额</div>
                <div class="data-value">{{ financialData.deliveryRefund }}元</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第四行：待处理事项（对齐 views/index.vue 布局） -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card>
          <template #header>
            <span class="section-title">待处理事项</span>
          </template>
          <div class="pending-items">
            <div class="pending-item">
              <span class="item-name">待处理开店申请</span>
              <span class="item-count" :class="{ 'highlight': pendingData.storeApplications > 0 }">
                {{ pendingData.storeApplications }}
              </span>
            </div>
            <div class="pending-item">
              <span class="item-name">待处理提现申请</span>
              <span class="item-count" :class="{ 'highlight': pendingData.withdrawalApplications > 0 }">
                {{ pendingData.withdrawalApplications }}
              </span>
            </div>
            <div class="pending-item">
              <span class="item-name">待处理变更资料申请</span>
              <span class="item-count" :class="{ 'highlight': pendingData.profileChangeApplications > 0 }">
                {{ pendingData.profileChangeApplications }}
              </span>
            </div>
            <div class="pending-item">
              <span class="item-name">待处理退款申请</span>
              <span class="item-count" :class="{ 'highlight': pendingData.refundApplications > 0 }">
                {{ pendingData.refundApplications }}
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 统计区：商家总页 + 用户总览（仅布局对齐 index.vue） -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 商家总页（保留原数据与文案） -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="stats-card">
          <template #header>
            <span class="card-header-title">商家总页</span>
          </template>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="8" class="stat-item">
              <div class="stat-value">{{ merchantStats.offline }}</div>
              <div class="stat-label">已下架</div>
            </el-col>
            <el-col :span="8" class="stat-item">
              <div class="stat-value">{{ merchantStats.online }}</div>
              <div class="stat-label">已上架</div>
            </el-col>
            <el-col :span="8" class="stat-item">
              <div class="stat-value">{{ merchantStats.total }}</div>
              <div class="stat-label">全部商家</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>

      <!-- 用户总览（保留原数据与文案） -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12">
        <el-card class="stats-card">
          <template #header>
            <span class="card-header-title">用户总览</span>
          </template>
          <el-row :gutter="20" class="stats-row">
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ userStats.todayNew }}</div>
              <div class="stat-label">今日新增</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ userStats.yesterdayNew }}</div>
              <div class="stat-label">昨日新增</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ userStats.monthNew }}</div>
              <div class="stat-label">本月新增</div>
            </el-col>
            <el-col :span="6" class="stat-item">
              <div class="stat-value">{{ userStats.total }}</div>
              <div class="stat-label">会员总数</div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
    </el-row>

    <!-- 订单统计 + 图表） -->
    <el-row :gutter="20" style="margin-top: 20px;">
      <!-- 订单统计 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card class="stats-card">
          <template #header>
            <span class="card-header-title">订单统计</span>
          </template>
          <div class="order-stats">
            <div class="order-stat-item">
              <div class="stat-title">本月订单总数</div>
              <div class="stat-main-value">{{ orderStats.monthTotal }}</div>
              <div class="stat-compare" :class="orderStats.monthCompare.type">
                {{ orderStats.monthCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本周订单总数</div>
              <div class="stat-main-value">{{ orderStats.weekTotal }}</div>
              <div class="stat-compare" :class="orderStats.weekCompare.type">
                {{ orderStats.weekCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本月销售额</div>
              <div class="stat-main-value">{{ orderStats.monthSales }}</div>
              <div class="stat-compare" :class="orderStats.monthSalesCompare.type">
                {{ orderStats.monthSalesCompare.text }}
              </div>
            </div>
            <div class="order-stat-item">
              <div class="stat-title">本周销售额</div>
              <div class="stat-main-value">{{ orderStats.weekSales }}</div>
              <div class="stat-compare" :class="orderStats.weekSalesCompare.type">
                {{ orderStats.weekSalesCompare.text }}
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 图表区域 -->
      <el-col :xs="24" :sm="12" :md="16" :lg="16">
        <el-card class="chart-card">
          <template #header>
            <div class="chart-header">
              <div class="chart-title-wrapper">
                <span class="card-header-title">订单趋势</span>
                <el-select
                  v-model="chartDataType"
                  @change="handleDataTypeChange"
                  size="small"
                  style="margin-left: 15px; width: 120px;"
                >
                  <el-option label="订单数量" value="orders" />
                  <el-option label="销售额" value="sales" />
                  <el-option label="客户数" value="customers" />
                </el-select>
              </div>
              <div class="date-picker-wrapper">
                <el-date-picker
                  v-model="chartDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateRangeChange"
                  size="small"
                />
              </div>
            </div>
          </template>
          <div ref="chartContainer" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="AdminDashboard">
import { reactive, ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { Document, Money, User, ShoppingBag } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 概览数据
const overviewData = reactive({
  todayPaidOrders: 200,
  todayPaidAmount: 15600,
  pendingOrders: 23,
  pendingRefunds: 5
})

// 账户数据
const accountData = reactive({
  totalBalance: 125680,
  todayIncome: 15600,
  todayExpense: 3200
})

// 金融数据
const financialData = reactive({
  productPayment: 14200,
  deliveryFee: 1400,
  refundAmount: 800,
  deliveryRefund: 200
})

// 待处理数据
const pendingData = reactive({
  storeApplications: 3,
  withdrawalApplications: 2,
  profileChangeApplications: 1,
  refundApplications: 5
})

// 商家统计
const merchantStats = reactive({
  offline: 5,
  online: 34,
  total: 39
})

// 用户统计
const userStats = reactive({
  todayNew: 12,
  yesterdayNew: 8,
  monthNew: 156,
  total: 1256
})

// 订单统计原始数据
const orderStatsData = reactive({
  // 当前数据
  monthTotal: 10,
  weekTotal: 5,
  monthSales: 5,
  weekSales: 3,  // 新增

  // 上期数据（用于计算同比）
  previousMonthTotal: 9,
  previousWeekTotal: 5,
  previousMonthSales: 5,
  previousWeekSales: 2  // 新增
})

// 计算同比数据的函数（新增）
const calculateCompare = (current, previous, period = '上期') => {
  if (previous === 0) {
    return { text: '新增数据', type: 'increase' }
  }

  const changeRate = ((current - previous) / previous * 100).toFixed(1)
  const isIncrease = changeRate > 0
  const isEqual = changeRate == 0

  if (isEqual) {
    return { text: `同比${period} 持平`, type: 'no-data' }
  }

  return {
    text: `同比${period} ${isIncrease ? '+' : ''}${changeRate}%`,
    type: isIncrease ? 'increase' : 'decrease'
  }
}

// 订单统计计算属性（修改为计算属性）
const orderStats = computed(() => ({
  monthTotal: orderStatsData.monthTotal,
  weekTotal: orderStatsData.weekTotal,
  monthSales: orderStatsData.monthSales,
  weekSales: orderStatsData.weekSales,  // 新增
  monthCompare: calculateCompare(orderStatsData.monthTotal, orderStatsData.previousMonthTotal, '上月'),
  weekCompare: calculateCompare(orderStatsData.weekTotal, orderStatsData.previousWeekTotal, '上周'),
  monthSalesCompare: calculateCompare(orderStatsData.monthSales, orderStatsData.previousMonthSales, '上月'),
  weekSalesCompare: calculateCompare(orderStatsData.weekSales, orderStatsData.previousWeekSales, '上周')  // 新增
}))

// 图表相关
const chartContainer = ref(null)
const chartDateRange = ref(['2025-07-23', '2025-08-06'])
const chartDataType = ref('orders')
let chartInstance = null

// 图表数据获取方法（完善）
const fetchChartData = async (startDate, endDate, dataType = 'orders') => {
  // 假数据 - 生成日期范围内的数据点
  const dates = generateDateRange(startDate, endDate)

  // 根据数据类型生成不同的模拟数据
  let values = []
  let title = ''
  let unit = ''

  switch (dataType) {
    case 'orders':
      title = '每日订单数量'
      unit = '单'
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay()
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
        const baseOrders = isWeekend ? 15 : 8
        const randomFactor = 0.3 + Math.random() * 0.7
        return Math.floor(baseOrders * randomFactor)
      })
      break

    case 'sales':
      title = '每日销售额'
      unit = '元'
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay()
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
        const baseSales = isWeekend ? 1500 : 800
        const randomFactor = 0.5 + Math.random() * 0.8
        return Math.floor(baseSales * randomFactor)
      })
      break

    case 'customers':
      title = '每日客户数'
      unit = '人'
      values = dates.map((date) => {
        const dayOfWeek = new Date(date).getDay()
        const isWeekend = dayOfWeek === 0 || dayOfWeek === 6
        const baseCustomers = isWeekend ? 25 : 12
        const randomFactor = 0.4 + Math.random() * 0.9
        return Math.floor(baseCustomers * randomFactor)
      })
      break
  }

  return {
    dates,
    values,
    title,
    unit
  }
}

// 生成日期范围
const generateDateRange = (start, end) => {
  const dates = []
  const current = new Date(start)
  const endDate = new Date(end)

  while (current <= endDate) {
    dates.push(current.toISOString().split('T')[0])
    current.setDate(current.getDate() + 1)
  }
  return dates
}

// 初始化图表（完善）
const initChart = async () => {
  if (!chartContainer.value) return

  const chartData = await fetchChartData(chartDateRange.value[0], chartDateRange.value[1], chartDataType.value)

  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartContainer.value)

  const option = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0,0,0,0.8)',
      textStyle: {
        color: '#fff'
      },
      formatter: function(params) {
        const date = params[0].axisValue.replace('\n', ' ')
        const value = params[0].value
        return `${date}<br/>${chartData.title}: ${value}${chartData.unit}`
      }
    },
    grid: {
      left: '50px',
      right: '20px',
      top: '20px',
      bottom: '50px'
    },
    xAxis: {
      type: 'category',
      data: chartData.dates.map(date => {
        const d = new Date(date)
        return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}\n${d.getFullYear()}`
      }),
      axisLabel: {
        fontSize: 10,
        color: '#666'
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      axisLabel: {
        fontSize: 10,
        color: '#666',
        formatter: '{value}'
      },
      splitLine: {
        lineStyle: {
          color: '#e0e0e0'
        }
      }
    },
    series: [{
      data: chartData.values,
      type: 'line',
      smooth: true,
      lineStyle: {
        color: '#409EFF',
        width: 2
      },
      itemStyle: {
        color: '#409EFF'
      },
      symbol: 'circle',
      symbolSize: 4
    }]
  }

  chartInstance.setOption(option)
}

// 日期范围改变处理
const handleDateRangeChange = () => {
  if (chartDateRange.value && chartDateRange.value.length === 2) {
    initChart()
  }
}

// 数据类型改变处理
const handleDataTypeChange = () => {
  initChart()
}

// 页面加载时初始化图表
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

// 页面卸载时销毁图表
onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style scoped lang="scss">
.admin-dashboard {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 84px);
}

.overview-section {
  margin-bottom: 20px;
}

.overview-card {
  margin-bottom: 20px;

  .card-content {
    display: flex;
    align-items: center;
    padding: 20px;

    .card-icon {
      margin-right: 20px;
      width: 60px;
      height: 60px;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #409EFF;
      background: rgba(64, 158, 255, 0.1);
    }

    .card-info {
      flex: 1;

      .card-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 8px;
      }

      .card-value {
        font-size: 24px;
        font-weight: bold;
        color: #333;

        &.highlight {
          color: #f56c6c;
        }
      }
    }
  }
}

.section-title {
  font-weight: bold;
  color: #333;
  font-size: 16px;
}

.account-data,
.financial-data,
.pending-data {
  padding: 20px 0;

  .data-item {
    text-align: center;

    .data-label {
      font-size: 14px;
      color: #666;
      margin-bottom: 12px;
    }

    .data-value {
      font-size: 20px;
      font-weight: bold;
      color: #f56c6c;

      &.balance {
        color: #f56c6c;
      }

      &.income {
        color: #67c23a;
      }

      &.outcome {
        color: #f56c6c;
      }

      &.urgent {
        color: #f56c6c;
      }
    }
  }
}

.stats-card {
  height: 100%;

  .stats-row {
    padding: 10px 0;

    .stat-item {
      text-align: center;

      .stat-value {
        font-size: 20px;
        font-weight: bold;
        color: #f56c6c;
        margin-bottom: 8px;
      }

      .stat-label {
        font-size: 12px;
        color: #666;
      }
    }
  }
}

.order-stats {
  .order-stat-item {
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .stat-title {
      font-size: 14px;
      color: #666;
      margin-bottom: 8px;
    }

    .stat-main-value {
      font-size: 20px;
      font-weight: bold;
      color: #333;
      margin-bottom: 6px;
    }

    .stat-compare {
      font-size: 12px;
      font-weight: 500;

      &.no-data {
        color: #999;

        &::before {
          content: '→ ';
          font-size: 10px;
        }
      }

      &.increase {
        color: #67c23a;

        &::before {
          content: '↗ ';
          font-size: 10px;
        }
      }

      &.decrease {
        color: #f56c6c;

        &::before {
          content: '↘ ';
          font-size: 10px;
        }
      }
    }
  }
}

.chart-card {
  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .date-picker-wrapper {
      .el-date-editor {
        width: 250px;
      }
    }
  }

  .chart-container {
    height: 420px;  // 增加高度
    width: 100%;
  }
}

.pending-items {
  .pending-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .item-name {
      font-size: 14px;
      color: #666;
    }

    .item-count {
      font-size: 16px;
      font-weight: bold;
      color: #333;

      &.highlight {
        color: #f56c6c;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .overview-card .card-content {
    flex-direction: column;
    text-align: center;

    .card-icon {
      margin-right: 0;
      margin-bottom: 10px;
    }
  }

  .account-data,
  .financial-data,
  .pending-data {
    .el-col {
      margin-bottom: 20px;
    }
  }

  .chart-header {
    flex-direction: column;
    gap: 15px;

    .date-picker-wrapper .el-date-editor {
      width: 100%;
    }
  }
}
</style>